生成带有 YYYY 格式的随机年份的 Python 代码是什么?

huangapple go评论60阅读模式
英文:

How to Generate Random Year in Python with format YYYY?

问题

age=random.randint(20, 80),
英文:

I have this code to generate fake name, age, address, I want to know what is the line to generate fake year in YYYY format?

def create_fake_users(n):
    """Generate fake users."""
    faker = Faker()
    for i in range(n):
        user = User(name=faker.name(),
                    age=random.randint(20, 80),
                    address=faker.address().replace('\n', ', '),
                    phone=faker.phone_number(),
                    email=faker.email())
        db.session.add(user)
    db.session.commit()
    print(f'Added {n} fake users to the database.')

答案1

得分: 1

你可以使用faker来生成随机日期:

from faker import Faker
fake = Faker()

# 从今天开始的一百年
fake.date_between(start_date='today', end_date='+100y')
# datetime.date(2038, 5, 10)

# 过去一百年
fake.date_time_between(start_date='-100y', end_date='now')
# datetime.datetime(1989, 10, 7, 19, 47, 27)

如果你只想获取年份 YYYY

fake.date_between(start_date='today', end_date='+100y').year
# 2038

fake.date_time_between(start_date='-100y', end_date='now').year
# 1989
英文:

You can use faker to generate random dates as well:

from faker import Faker
fake = Faker()

#one hundred years from today
fake.date_between(start_date='today', end_date='+100y')
#datetime.date(2038, 5, 10)

# last one hundred years
fake.date_time_between(start_date='-100y', end_date='now')
#datetime.datetime(1989, 10, 7, 19, 47, 27)

If you just want the year in YYYY then:

fake.date_between(start_date='today', end_date='+100y').year
#2038

fake.date_time_between(start_date='-100y', end_date='now').year
#1989

答案2

得分: 1

我希望这对你的解决方案有用

from faker import Faker
import datetime
fake = Faker()
date = fake.date()
datetime_object = datetime.datetime.strptime(date, '%Y-%m-%d')
datetime_object.year
英文:

I hope, this works for your solution

from faker import Faker
import datetime
fake = Faker()
date = fake.date()
datetime_object = datetime.datetime.strptime(date, '%Y-%m-%d')
datetime_object.year

huangapple
  • 本文由 发表于 2023年2月8日 14:09:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75381941.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定